import React, { useEffect, useState } from 'react'
import { Button, Table, Popconfirm, message, Tree, Modal } from 'antd'
import axios from 'axios'
import {
  DeleteOutlined,
  UnorderedListOutlined
} from '@ant-design/icons'


export default function RoleList() {
  const [dataSource, setdataSource] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [rightList, setRightList] = useState([]);
  const [currentrightList, setCurrentrightList] = useState([]);
  const [currenId, setcurrenId] = useState(0);

  useEffect(() => {
    axios.get("/roles").then(res => {
      setdataSource(res.data)
    })
  }, [])

  useEffect(() => {
    axios.get("/rights?_embed=children").then(res => {
      res.data[0].children = ""
      setRightList(res.data)
    })
  }, [])

  const showModal = (item) => {
    setIsModalOpen(true);
    setCurrentrightList(item.rights)
    setcurrenId(item.id)
  };

  const handleOk = (item) => {
    setIsModalOpen(false);
    // 同步datasource
    setdataSource(dataSource.map(item => {
      if (item.id === currenId) {
        return {
          ...item,
          rights: currentrightList
        }
      } else {
        return item
      }
    }))

    // put
    axios.patch(`/roles/${currenId}`, { rights: currentrightList })
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      render: (id) => {
        return <b>{id}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
    },
    {
      title: 'roleType',
      dataIndex: 'roleType',
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => {
              confirm(item)
            }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger shape="circle" icon={<DeleteOutlined />}></Button>
          </Popconfirm>

          <Button type="primary" shape="circle" icon={<UnorderedListOutlined />} onClick={() => { showModal(item) }} />

        </div>
      }

    },
  ];

  const delMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/roles/${item.id}`)
  };

  const confirm = (item) => {
    message.success('Click on Yes');
    delMethod(item)
  };
  const cancel = (e) => {
    // console.log(e);
    // message.error('Click on No');
  };

  const onSelect = (selectedKeys, info) => {
    // console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys, info) => {
    // console.log('onCheck', checkedKeys, info);
    setCurrentrightList(checkedKeys)
  };

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />

      <Modal title="权限分配" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Tree
          checkable
          // defaultExpandedKeys={["/home", "/user-manage"]}
          // defaultSelectedKeys={["/home", "/user-manage"]}
          checkedKeys={currentrightList}
          onSelect={onSelect}
          onCheck={onCheck}
          treeData={rightList}
          checkStrictly={true} // checkable 状态下节点选择完全受控（父子节点选中状态不再关联）
        />
      </Modal>
    </div>
  )
}
